import { createRouter, createWebHistory } from "vue-router";
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { getUserMenu } from '@/api/system/user'
import staticRouter from "./modules/staticRouter";
import { GetRouter } from "@/stores/modules/RouterList";
import LayoutView from "@/view/layout/index.vue"
import { ElMessage } from 'element-plus'
// const store = GetRouter()
let redirectCode: any = ""
const routes: any = [
    {
        path: "/login",
        name: "login",
        component: () => import("@/view/login/index.vue"),
    },
    {
        path: "/404",
        component: () => import("@/view/404/index.vue")
    },
    {
        path: "/:catchAll(.*)", // 不识别的path自动匹配404
        redirect: '/404',
    },
];
const router = createRouter({
    history: createWebHistory(),
    routes: [...staticRouter, ...routes],
});

let routeList: any = []
const addDynamicRoute = (data: any, routeList: any) => {
    for (let i = 0; i < data.length; i++) {
        const item = data[i];
        if (item.children && item.children.length > 0) {
            routeList[i] = item
            routeList[i].component = modules[item.component]
            if (!routeList[i].component) delete routeList[i].component
            addDynamicRoute(item.children, routeList[i]?.children)
        } else {
            routeList[i] = item
            routeList[i].component = modules[item.component]
            if (!routeList[i].component) delete routeList[i].component
            //指定根路由@layoutName
            router.addRoute("layoutName", { path: item.path, component: routeList[i].component })
        }
    }
}
let num: any = 0
// import.meta.glob('../view/**/*.vue') 获取文件所有的view下的vue文件通过addDynamicRoute动态注册路由
let modules = import.meta.glob('../view/**/*.vue')
const { token } = localStorage.getItem("token") ? JSON.parse(localStorage.getItem("token") as any) : { token: null }
const { visitor } = localStorage.getItem("visitor") ? JSON.parse(localStorage.getItem("visitor") as any) : { visitor: null }
if (token && !visitor) {
    const dt = await getUserMenu({ token: token })
    redirectCode = dt.data.find((item: any) => item.redirect).redirect
    router.addRoute({ name: 'layoutName', redirect: redirectCode, path: '/', component: LayoutView, children: [] }) //动态添加根路由
    num = router.getRoutes().findIndex(item => item.path === '/')
    addDynamicRoute(dt.data, routeList)
    router.getRoutes()[num].children = [...routeList]
}

router.beforeEach((to: any, from: any, next: any) => {
    const { token } = localStorage.getItem("token") ? JSON.parse(localStorage.getItem("token") as any) : { token: null }
    GetRouter().SetRouter(router.getRoutes()[num])
    NProgress.start();
    // GetRouter().visitor 是否是游客登录 游客登录走静态路由
    if (!GetRouter().visitor) {
        if (!token && to.path !== "/login") {
            ElMessage({
                message: '请先完成登录！',
                type: 'error',
            })
            return next({ path: "/login" });
        }
    }
    //已登陆
    if (token && to.path == "/login") return next({ path: "/" });
    next();
});

router.afterEach((to: any, from: any, next: any) => {
    NProgress.done();
    // try {
    //     //设置标题
    //     if (to.meta.name) {
    //         document.title = to.meta.name;
    //     }
    // } catch (err) { }
    // let routerList = to.matched;
    // //顶部面包屑
    // store.commit("setCrumbList", routerList);
    // //目前左边导航选中的active
    // store.commit("SET_CURRENT_MENU", to.name);
});
export default router;